package managers
{
	import assets.Globals;
	
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import gameobjects.Map;
	import gameobjects.Tower;
	
	import logic.FieldCalc;

	public class TowerDropper
	{
		private var active:Boolean = false;
		
		private var handler:Function;
		
		public function TowerDropper(handler:Function)
		{
			this.handler = handler;
		}
		
		private var tower:Tower;
		
		private function positionTower(x:Number, y:Number):void
		{
			const newPoint:Point = FieldCalc.calcTile(x, y);
			tower.x = newPoint.x;
			tower.y = newPoint.y;
			const field:Point = FieldCalc.calcIndex(x, y);
			if (Globals.towersMap.isAvailable(field.x, field.y))
				tower.show();
			else
				tower.hide();
		}
		
		public function start(tower:Tower):void
		{
			active = true;
			Globals.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			Globals.stage.addEventListener(MouseEvent.CLICK, mouseClickHandler);
			this.tower = tower;
			Globals.game.addChild(tower);
			positionTower(Globals.stage.mouseX, Globals.stage.mouseY);
		}
		
		private function mouseMoveHandler(event:MouseEvent):void
		{
			positionTower(event.stageX, event.stageY);
		}
		
		private function mouseClickHandler(event:MouseEvent):void
		{
			const field:Point = FieldCalc.calcIndex(event.stageX, event.stageY);
			if (Globals.towersMap.isAvailable(field.x, field.y)) {
				active = false;
				Globals.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
				Globals.stage.removeEventListener(MouseEvent.CLICK, mouseClickHandler);
				handler(field.x, field.y, tower);
				tower.show();
			}
		}
		
		public function stop():void
		{
			active = false;
			Globals.game.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			Globals.game.removeEventListener(MouseEvent.CLICK, mouseClickHandler);
			Globals.game.removeChild(tower);
		}
		
		public function isActive():Boolean
		{
			return active;
		}
	}
}
